import { createStore } from "vuex";
import { Connection, PublicKey } from "@solana/web3.js";
import { Program, AnchorProvider, setProvider } from "@coral-xyz/anchor";
import idl from "../idl/blindbox.json";
const programId = new PublicKey(idl.metadata.address);
export const store = createStore({
  state() {
    return {
      autoConnect: true,
      userSOLBalance: 0,
      workspace: {},
    };
  },
  mutations: {
    setAutoConnect(state) {
      state.autoConnect = !state.autoConnect;
    },
    setBalance(state, payload) {
      state.userSOLBalance = payload.balance;
    },
    async initWorkspace(state, payload) {
      return await window.solana.connect().then((response) => {
        const wallet = window.solana;
        if (wallet) {
          const commitment = "confirmed";
          //const connection = new Connection('https://devnet.helius-rpc.com/?api-key=78483ff4-5689-45fe-a8da-f569c3894e07',commitment);

          const connection = new Connection(
            "https://solana-devnet.g.alchemy.com/v2/7UkAPiRCVyTwF7Mo7u6V9KH8eV1Xe01z",
            commitment
          );

          const provider = new AnchorProvider(
            connection,
            wallet,
            AnchorProvider.defaultOptions()
          );
          setProvider(provider);

          //console.log(idl);

          const program = new Program(idl, programId);
          // 填充workspace对象
          state.workspace = {
            value: {
              wallet,
              connection,
              provider,
              program,
            },
          };
          payload.callback();
        } else {
          console.error("Wallet not found!");
        }
      });
    },
  },
});
